package com.moyu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.moyu.common.core.enums.ResultCode;
import com.moyu.common.security.exception.ServiceException;
import com.moyu.user.domain.permission.Permission;
import com.moyu.user.domain.role.Role;
import com.moyu.user.mapper.RoleMapper;
import com.moyu.user.service.IPermissionService;
import com.moyu.user.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author 赵彦博
 * @Date 2024/11/19 17:40
 */
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private IPermissionService permissionService;


    @Override
    public Role createRole(Role role) {
        if (queryByRoleName(role.getName()) != null) {
            throw new ServiceException(ResultCode.AILED_ROLE_EXISTS);
        }
        roleMapper.insert(role);
        return role;
    }

    @Override
    public Role queryByRoleName(String name) {
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        Role role = roleMapper.selectOne(queryWrapper
                .select(Role::getId,Role::getName,Role::getCreateTime,Role::getUpdateTime)
                .eq(Role::getName, name));
        return role;
    }

    @Override
    public List<Role> listByUsername(String username) {
        return roleMapper.listByUsername(username);
    }

    @Override
    public Role update(Role role) {
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.update(role);
        return queryByRoleName(role.getName());
    }


    @Override
    public boolean delete(Long id) {
        return roleMapper.delete(id) > 0;
    }

    @Override
    public List<Role> list() {
        return roleMapper.list();
    }

    @Override
    public List<Permission> listPermission(Long id, boolean treeMode) {
        return permissionService.listByRoleId(id, treeMode);
    }

    @Override
    public void createPermission(Long id, List<Permission> permissions) {
        if (!permissions.isEmpty()) {
            roleMapper.insertPermission(id, permissions);
        }
    }

    @Override
    public void updatePermission(Long id, List<Permission> permissions) {
        if (!permissions.isEmpty()) {
            roleMapper.deletePermission(id);
            roleMapper.insertPermission(id, permissions);
        }
    }
}
